package logic

import (
	"context"
	"io"
	"net/http"

	"goNutpi/internal/svc"
	"goNutpi/internal/types"

	"github.com/tidwall/gjson"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpc"
)

type AskDetailLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAskDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AskDetailLogic {
	return &AskDetailLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AskDetailLogic) AskDetail(req *types.AskDetailReq) (resp *types.AskDetailResp, err error) {
	// todo: add your logic here and delete this line
	url := "https://api.nutpi.net/question?questionId=" + req.QId
	res, err_ := httpc.Do(l.ctx, http.MethodGet, url, nil)
	if err_ != nil {
		l.Error(err_)
		return nil, err_
	}
	defer res.Body.Close()
	body, err := io.ReadAll(res.Body)
	if err != nil {
		l.Errorf("Failed to read response body:", err)
		return nil, err
	}
	//格式化输出json
	//var str bytes.Buffer
	//_ = json.Indent(&str, []byte(body), "", "    ")
	//l.Debugf("formated: ", str.String())
	//l.Debug(keyValue)
	var respData types.AskDetailData

	rec := gjson.ParseBytes(body)

	respData.ID = rec.Get("id").String()
	respData.Title = rec.Get("title").String()
	respData.Summary = rec.Get("summary").String()
	respData.Content = rec.Get("content").String()
	respData.PostTime = rec.Get("postTime").String()
	respData.Nickname = rec.Get("nickname").String()
	//l.Infof("id: %s, title: %s\n", respData.ID, respData.Title)
	respData.Content = rec.Get("content").String()
	respData.ViewTotal = rec.Get("nickname").String()
	respData.AnswerTotal = rec.Get("answerTotal").String()
	//t := reflect.TypeOf(keyVal["count"])
	//l.Debugf("Type: %v\n", t)

	if res.StatusCode >= 200 && res.StatusCode < 400 {
		resp = &types.AskDetailResp{
			Code:    0,
			Message: res.Status,
			Data:    respData,
		}
	} else {
		resp = &types.AskDetailResp{
			Code:    res.StatusCode,
			Message: res.Status,
			Data:    types.AskDetailData{},
		}
	}
	return resp, nil
}
